import { request, downloadBlobFile } from 'src/utils';

export interface RoleDto {
  roleId: IdType; // 角色ID
  roleCode: string; // 角色编码
  roleName: string; // 角色名称
  remark: string; // 备注说明
  disabled: boolean; // 是否作废
  updatedBy: string; // 修改人
  updatedTime: Date; // 修改时间
  menuIds?: number[];
}

const baseUrl = '/api/system/role';

/**
 * 查单个
 */
export function readData(roleId: IdType): Promise<RoleDto> {
  return request.get(baseUrl + '/' + roleId);
}

/**
 * 查集合
 */
export function queryList(query: PageQuery): Promise<PageResult<RoleDto>> {
  return request.get(baseUrl, { params: query });
}

/**
 * 查角色下拉选项
 */
export function getRoleOptions(): Promise<SelectOption[]> {
  return new Promise((resolve, reject) => {
    queryList({ pageSize: 0, pageNo: 1, search: '' })
      .then((data) => {
        resolve(data.dataList.map((a) => ({ value: a.roleId, label: a.roleName, disabled: a.disabled }) as SelectOption));
      })
      .catch((err) => reject(err));
  });
}

/**
 * 新增，修改
 */
export function saveOrUpdate(role: RoleDto): Promise<RoleDto> {
  return role.roleId ? request.put(baseUrl + '/' + role.roleId, role) : request.post(baseUrl, role);
}

/**
 * 删除
 */
export function deleteByIds(ids: IdType[]): Promise<void> {
  return request.delete(baseUrl, { params: { ids } });
}

/**
 * 导出
 */
export function exportData(query: PageQuery): Promise<void> {
  return new Promise((resolve, reject) => {
    request
      .get(baseUrl + '/export', { params: query, responseType: 'blob' })
      .then((res) => {
        downloadBlobFile(res);
        resolve();
      })
      .catch((err) => reject(err));
  });
}

export default { readData, queryList, saveOrUpdate, deleteByIds, exportData } as CrudApi<RoleDto>;
